// 书签api
var bookMarks = chrome.bookmarks;
var storage = chrome.storage.local;
/*
var owner = '';
var repo = '';
var path = '';
var fileUrl = 'https://gitee.com/api/v5/repos/' + owner + '/' + repo + '/contents/' + path;
var accessToken = '';
*/
var inputInfo = [
    'owner', 'repo', 'path', 'accessToken', 'branch'
];

// 书签列表
var bookMarkList = [];

var layer;
layui.use('layer', function () {
    layer = layui.layer;
});
var updatePercent = (percent) => {
    $('#handlePercent').attr('handlePercent', percent + '%');
}

$(function () {
    init();
})

function init() {
    for (var f in inputInfo) {
        var field = inputInfo[f];
        var elem = $("input[name='" + field + "']");
        elem.keyup(function () {
            setUserInfo($(this).attr('name'), $.trim($(this).val()));
        });
        var userInfo = getUserInfo();
        if (userInfo.hasOwnProperty(field)) {
            elem.val(userInfo[field]);
        }
    }
}

/**
 * 获取用户信息
 * @returns {Promise<unknown>}
 */
function getUserInfo(field = '', defaultValue = {}) {
    var userInfo = localStorage.getItem('userInfo');
    if (isNull(userInfo)) {
        userInfo = {};
    } else {
        userInfo = JSON.parse(userInfo);
    }
    if (field) {
        if (userInfo.hasOwnProperty(field)) {
            return userInfo[field];
        }
        return defaultValue;
    }
    return userInfo;
}

/**
 * 设置用户信息
 * @param field
 * @param value
 */
function setUserInfo(field, value) {
    var userInfo = getUserInfo();
    userInfo[field] = value;
    localStorage.setItem('userInfo', JSON.stringify(userInfo));
}

/**
 * 获取授权码
 * @returns {string}
 */
function getAccessToken() {
    return getUserInfo('accessToken', '');
}

function getFileUrl() {
    var owner = getUserInfo('owner', '');
    var repo = getUserInfo('repo', '');
    var path = getUserInfo('path', '');
    return 'https://gitee.com/api/v5/repos/' + owner + '/' + repo + '/contents/' + path;
}

/**
 * 测试
 */
$('#testButton').click(function () {
    /*bookMarks.getTree((bookMarkArr) => {
        console.log(JSON.stringify(bookMarkArr));
    });*/
    /*
    chrome.runtime.sendMessage({type:'checkFlag'},(res)=>{
    })
    */
    var loadingIndex = layer.load(0, {shade: [0.1, '#fff']});
    getFileInfo(0).then((res) => {
        layer.alert('校验成功');
        layer.close(loadingIndex);
    }).catch(res => {
        layer.close(loadingIndex);
    })
});

/**
 * 清除
 */
$('#clean').click(function () {
    layer.confirm('确定要删除之前的书签并重新导入吗?', {icon: 3, title: '提示'}, function (confirmIndex) {
        var loadingIndex = layer.load(0, {shade: [0.1, '#fff']});
        bookMarks.getTree(bookMarkArr => {
            handleRemove(bookMarkArr)
            layer.close(loadingIndex)
        })
        layer.close(confirmIndex);
    });
});

/**
 * 导入
 */
$('#import').click(function () {
    layer.confirm('确定要删除之前的书签并重新导入吗?', {icon: 3, title: '提示'}, function (confirmIndex) {
        var loadingIndex = layer.load(0, {shade: [0.1, '#fff']});
        getFileInfo().then((fileInfo) => {
            if (!fileInfo.hasOwnProperty('content')) {
                layer.close(loadingIndex);
                layer.alert('书签内容为空，先推送。')
                return;
            }
            var content = JSON.parse(Base64.decode(fileInfo.content));
            saveContent(content).then(res=>{
                layer.close(loadingIndex);
            })
        }).catch(res => {
            layer.close(loadingIndex);
        })
        layer.close(confirmIndex);
    });
});

/**
 * 移除书签
 * @param bookMarkArr
 */
function handleRemove(bookMarkArr) {
    for (var k in bookMarkArr) {
        var item = bookMarkArr[k]
        if (item.hasOwnProperty('children')) {
            var children = item.children;
            if (parseInt(item.id) < 3) {
                handleRemove(children)
            } else {
                bookMarks.removeTree(item.id, res => {
                    console.log('移除', res);
                })
            }
        }
        if (parseInt(item.id) > 3) {
            handleRemove(children)
            bookMarks.remove(item.id, res => {
                console.log('移除', res);
            })
        }
    }
}

/**
 * 导入书签保存
 * @param content
 * @param parentId
 * @param setParentId
 * @returns {Promise<void>}
 */
async function saveContent(content, parentId = '1', setParentId = '1') {
    for (var i in content) {
        var item = content[i];
        if (item.parentId == parentId) {
            var save = {
                parentId: setParentId,
                index: item.index,
                title: item.title,
            };
            if (item.hasOwnProperty('url')) {
                save.url = item.url;
            }
            console.log(item)
            var newId = await new Promise(resolve => {
                bookMarks.create(save, function (r) {
                    if (isNull(r)) {
                        resolve('0')
                    }
                    console.log('新增');
                    console.log(r);
                    resolve(r.id)
                });
            })
            if (newId == '0') {
                continue;
            }
            saveContent(content, item.id, newId)
        }
    }
}

/**
 * 获取书签信息
 */
$('#pullBookMark').click(function () {
    layer.confirm('确定拉取书签?', {icon: 3, title: '提示'}, function (confirmIndex) {
        //do something
        var loading = layer.load(0, {shade: [0.1, '#fff']})
        getFileInfo().then((fileInfo) => {
            if (!fileInfo.hasOwnProperty('content')) {
                layer.close(loading);
                layer.alert('书签内容为空，先推送。')
                return;
            }
            var content = JSON.parse(Base64.decode(fileInfo.content));

            /*
             // 进度条显示
             $('.c3').show();
             var percent = 0;
             var total = content.length;*/
            var handleContent = async function (content) {
                for (var k in content) {
                    var item = content[k];

                    var info = await new Promise(((resolve, reject) => {
                        // 找得到时
                        bookMarks.get(item.id, (res) => {
                            if (isNull(res)) {
                                resolve({});
                            }
                            var info = res[0];
                            resolve(info);
                        });

                    }))
                    // 未找到书签
                    if (isNull(info)) {
                        console.log(item);
                        // 查找并删除
                        await new Promise(resolve => {
                            bookMarks.search(item.title, rs => {
                                if (isNull(rs)) {
                                    resolve()
                                }
                                for (var s in rs) {
                                    var sItem = rs[s];
                                    if (!(item.parentId == sItem.parentId && item.title == sItem.title)) {
                                        continue;
                                    }
                                    if (item.hasOwnProperty('url')) {
                                        if (!sItem.hasOwnProperty('url')) {
                                            continue;
                                        }
                                        if (item.url == sItem.url) {
                                            bookMarks.remove(item.id, rs => {
                                                console.log('移除', rs)
                                                resolve();
                                            });
                                        }
                                    } else {
                                        bookMarks.remove(item.id, rs => {
                                            console.log('移除', rs)
                                            resolve();
                                        });
                                    }
                                }
                                resolve();
                            });
                        })
                        // 添加
                        await new Promise((resolve => {
                            var save = {
                                parentId: item.parentId,
                                index: item.index,
                                title: item.title,
                            };
                            if (item.hasOwnProperty('url')) {
                                save.url = item.url;
                            }
                            bookMarks.create(save, function (r) {
                                console.log('新增');
                                console.log(r);
                                resolve(r)
                            });
                        }));
                        continue;
                    }
                    var bool = false;
                    // 判断是否有变动
                    for (var f in info) {
                        var value = info[f];
                        if (item[f] != value) {
                            bool = true;
                            break;
                        }
                    }
                    if (bool) {
                        var updateInfo = {
                            title: item.title,
                            url: item.url
                        }
                        await new Promise((resolve => {
                            bookMarks.update(info.id, updateInfo, function (r) {
                                console.log('更新');
                                console.log(r);
                                resolve(r)
                            });
                        }));

                        if (item.parentId != info.parentId || item.index != info.index) {
                            await new Promise((resolve => {
                                moveInfo = {
                                    parentId: item.parentId,
                                    index: item.index
                                }
                                bookMarks.move(info.id, moveInfo, function (r) {
                                    console.log('移动');
                                    console.log(r);
                                    resolve(r)
                                });
                            }))
                        }
                    }
                    // percent++;
                    // updatePercent(percent/total);
                }
            }
            handleContent(content);
            // $('.c3').hide();
            layer.close(loading);
            layer.msg('拉取成功');
        }).catch(res => {
            layer.close(loading);
        });
        layer.close(confirmIndex);
    });

});

$('#updateBookMark').click(function () {
    layer.confirm('确定推送书签?', {icon: 3, title: '提示'}, function (confirmIndex) {
        bookMarks.getTree((bookMarkArr) => {
            handelTree(bookMarkArr);
            updateBookMark(bookMarkList);
        });
        layer.close(confirmIndex);
    })

});

/**
 * 将树形书签处理为一维数组
 * @param bookMarkArr
 */
function handelTree(bookMarkArr) {
    for (var k in bookMarkArr) {
        var item = bookMarkArr[k]
        if (item.hasOwnProperty('children')) {
            var children = item.children;
            delete item['children'];
            handelTree(children)
        }
        bookMarkList.push(item);
    }
}

/**
 * 获取文件信息
 * @returns {Promise<*>}
 */
async function getFileInfo(isTest = 1) {
    var fileInfo = await new Promise((resolve, reject) => {
        storage.get('fileInfo', function (res) {
            resolve(res.fileInfo);
        })
    });
    /*if (!isNull(fileInfo) && isTest == 1) {
        return fileInfo;
    }*/
    var url = getFileUrl() + "?access_token=" + getAccessToken();
    fileInfo = await new Promise((resolve, reject) => {
        $.ajax({
            url: url, method: 'get', data: {}, success: function (res) {
                if (isNull(res)) {
                    layer.alert('文件路径错误');
                    reject();
                }
                storage.set({'fileInfo': res})
                // console.log(res);
                resolve(res);
            }, dataType: 'json', error: function (xhr, status, error) {
                console.log(xhr, status, error)
                layer.alert(xhr.responseJSON.message)
            }
        });
    })
    return fileInfo;
}

/**
 * 修改书签
 * @param content
 */
function updateBookMark(content) {
    var postContent = Base64.encode(JSON.stringify(content))
    var index = layer.load(0, {shade: [0.1, '#fff']})
    getFileInfo().then((fileInfo) => {
        $.ajax({
            url: getFileUrl(),
            type: 'put',
            dataType: 'json',
            data: {
                access_token: getAccessToken(),
                content: postContent,
                sha: fileInfo.sha,
                message: "书签提交",
                branch: getUserInfo('branch', 'master')
            }, success: function (res) {
                console.log(res);
                storage.remove('fileInfo')
                layer.close(index);
                layer.msg('推送成功')
            }, error: function (xhr, status, error) {
                layer.close(index);
                layer.alert(xhr.responseJSON.message)
            }
        })
    }).catch(res => {
        layer.close(index);
    });
}
